
package com.eworking.eim.receive;

import java.io.File;
import java.util.HashMap;

import android.content.ContentValues;
import android.text.TextUtils;

import com.eworking.eim.EIMCallBack;
import com.eworking.eim.EIMConfig;
import com.eworking.eim.EIMConstants;
import com.eworking.eim.cloud.CloudOperationCallback;
import com.eworking.eim.cloud.HttpFileManager;
import com.eworking.eim.encrypt.EIMEncryptUtils;
import com.eworking.eim.message.EIMMessage;
import com.eworking.eim.message.EIMMessageTable;
import com.eworking.eim.message.body.FileMessageBody;
import com.eworking.eim.message.body.ImageMessageBody;
import com.eworking.eim.message.body.VideoMessageBody;
import com.eworking.eim.util.EIMLog;
import com.eworking.eim.util.PathUtil;

public class EIMReceiveMessageThread implements Runnable {
    
    /** 日志输出标记 */
    private static final String _TAG = EIMReceiveMessageThread.class.getSimpleName();
    
    /** 消息实体 */
    private EIMMessage message = null;
    
    /** 是否加密 */
    private boolean isEncrypted = false;
    
    public EIMReceiveMessageThread(EIMMessage message, boolean isEncrypted) {
        this.message = message;
        this.isEncrypted = isEncrypted;
    }
    
    @Override
    public void run() {
        // 设置消息状态为处理中
        this.message.status = EIMMessage.Status.INPROGRESS;
        final FileMessageBody fileMessageBody = (FileMessageBody) message.getMessageBody();
        try {
            // 本地地址
            String strLocalURL = fileMessageBody.getLocalUrl();
            // 远程地址
            String strRemoteURL = fileMessageBody.getRemoteUrl();
            
            // 本地缩略图地址
            String strLocalThumbURL = "";
            if (this.message.type == EIMMessage.Type.IMAGE) {
                // 图片缩略图远程地址
                strRemoteURL = ((ImageMessageBody) fileMessageBody).getThumbnailUrl();
                // 缩略图名称
                String strThumbName =
                    (new StringBuilder("th")).append(strRemoteURL.substring(strRemoteURL.lastIndexOf("/") + 1))
                        .toString();
                strLocalThumbURL =
                    (new StringBuilder()).append(PathUtil.getInstance().getImagePath().getPath()).append("/")
                        .append(strThumbName).toString();
            } else if (this.message.type == EIMMessage.Type.VIDEO) {
                // 视频缩略图远程地址
                strRemoteURL = ((VideoMessageBody) fileMessageBody).getThumbnailUrl();
                // 缩略图名称
                String strThumbName =
                    (new StringBuilder("th")).append(strRemoteURL.substring(strRemoteURL.lastIndexOf("/") + 1))
                        .toString();
                strLocalThumbURL =
                    (new StringBuilder()).append(PathUtil.getInstance().getVideoPath().getPath()).append("/")
                        .append(strThumbName).toString();
            } else {
                strLocalThumbURL = strLocalURL;
            }
            // 文件下载
            HttpFileManager httpFileManager =
                new HttpFileManager(EIMConfig.getInstance().getApplicationContext(), EIMConfig.ARCHIVE_SERVER);
            HashMap<String, String> paramMap = new HashMap<String, String>();
            paramMap.put("Authorization",
                (new StringBuilder("Bearer ")).append(EIMConfig.getInstance().getAccessToken()).toString());
            paramMap.put("Accept", "application/octet-stream");
            if (message.type == EIMMessage.Type.IMAGE) {
                if (fileMessageBody.secret != null) {
                    paramMap.put(EIMConstants._SHARE_SERCRET, fileMessageBody.secret);
                }
                paramMap.put("thumbnail", "true");
            } else if (message.type == EIMMessage.Type.VIDEO) {
                if (!TextUtils.isEmpty(((VideoMessageBody) fileMessageBody).thumbnailSecret)) {
                    paramMap.put(EIMConstants._SHARE_SERCRET, ((VideoMessageBody) fileMessageBody).thumbnailSecret);
                }
                paramMap.put("thumbnail", "true");
            }
            
            final String strTempLocalThumbURL = strLocalThumbURL;
            // 下载文件
            httpFileManager.downloadFile(strLocalURL, strTempLocalThumbURL, paramMap, new CloudOperationCallback() {
                
                @Override
                public void onSuccess(String paramString) {
                    File file = new File(strTempLocalThumbURL);
                    if (isEncrypted) {
                        EIMEncryptUtils.decryptFile(file.getAbsolutePath(), message.getFrom());
                    }
                    EIMLog.d(_TAG, "下载文件," + strTempLocalThumbURL);
                    fileMessageBody.downloaded = true;
                    message.status = EIMMessage.Status.SUCCESS;
                    // 更新消息状态
                    updateMsgState();
                    message.progress = 100;
                    if (fileMessageBody.callBack != null) {
                        fileMessageBody.callBack.onProgress(100, null);
                        fileMessageBody.callBack.onSuccess();
                    }
                }
                
                @Override
                public void onProgress(int status) {
                    message.progress = status;
                    if (fileMessageBody.callBack != null) {
                        fileMessageBody.callBack.onProgress(status, null);
                    }
                }
                
                @Override
                public void onError(String paramString) {
                    message.status = EIMMessage.Status.FAIL;
                    // 更新消息状态
                    updateMsgState();
                    if (fileMessageBody.callBack != null)
                        fileMessageBody.callBack.onError(EIMCallBack.ERROR_EXCEPTION, paramString);
                }
            });
        } catch (Exception e) {
            message.status = EIMMessage.Status.FAIL;
            updateMsgState();
            fileMessageBody.downloaded = false;
            if (fileMessageBody.callBack != null) {
                fileMessageBody.callBack.onError(EIMCallBack.ERROR_EXCEPTION, e.getMessage());
            }
        }
        
    }
    
    /**
     * 更新数据库中消息的状态
     */
    private void updateMsgState() {
        ContentValues values = new ContentValues();
        values.put(EIMMessageTable.Fields._MSG_STATUS, Integer.valueOf(this.message.status.ordinal()));
        EIMMessageTable.getInstance().updateMessage(this.message.getMsgId(), values);
    }
}
